import {Car} from './Car.jsx'
import {audios, playAudio} from '../../utils/AudioManager.jsx'
import {useRef, useState} from 'react'
import {useFrame} from '@react-three/fiber'
import {__GAME_CAR_KEY__} from '../UI.jsx'
import {MathUtils} from 'three'

const SWITCH_DURATION = 600;

export const CarSwitcher = ({player}) => {
  const changedCarAt = useRef(0)
  const container = useRef()
  const [carModel, setCurrentCarModel] = useState(player.getState(__GAME_CAR_KEY__))
  useFrame(() => {
    const timeSinceChange = Date.now() - changedCarAt.current
    if (timeSinceChange < SWITCH_DURATION / 2) {
      container.current.rotation.y +=
        2 * (timeSinceChange / SWITCH_DURATION / 2)
      container.current.scale.x =
        container.current.scale.y =
          container.current.scale.z =
            1 - timeSinceChange / SWITCH_DURATION / 2
    } else if (timeSinceChange < SWITCH_DURATION) {
      container.current.rotation.y +=
        4 * (1 - timeSinceChange / SWITCH_DURATION)
      container.current.scale.x =
        container.current.scale.y =
          container.current.scale.z =
            timeSinceChange / SWITCH_DURATION
      if (container.current.rotation.y > Math.PI * 2) {
        container.current.rotation.y -= Math.PI * 2
      }
    }
    if (timeSinceChange >= SWITCH_DURATION) {
      container.current.rotation.y = MathUtils.lerp(
        container.current.rotation.y,
        Math.PI * 2,
        0.1
      )
    }
  }, [])
  const newCar = player.getState(__GAME_CAR_KEY__)
  if (newCar !== carModel) {
    playAudio(audios.car_start)
    changedCarAt.current = Date.now()
    setTimeout(() => {
      setCurrentCarModel(newCar)
    }, SWITCH_DURATION / 2)
  }
  return (
    <group ref={container}>
      <Car model={carModel}/>
    </group>
  )
}
